package protocol

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"unsafe"
)

// 单片机端口7700
// 上位机端口8800
var UP_PORT int = 8800

type Protocol struct {
	UdpSocke *net.UDPConn
	IsInit   bool
}

// 数据包
type Package struct {
	RawData    []byte
	remoteAddr *net.UDPAddr
}

// 转速数据包
type FanSpeedPackege struct {
	Cmd uint16
	Cpu uint8
	Gpu uint8
}

// 初始化,只能调用一次
func (a *Protocol) Init() {
	if a.IsInit {
		return
	}

	addr, err := net.ResolveUDPAddr("udp4", ":"+strconv.Itoa(UP_PORT))
	ErrCheck(err)
	a.UdpSocke, err = net.ListenUDP("udp", addr)
	ErrCheck(err)
	a.IsInit = true
}

// 接收一个数据包
func (a *Protocol) Receive() (pkg Package, cmd uint16) {
	var remoteData = make([]byte, 1024)
	outpkg := Package{}
	var outCmd uint16 = 0
	//接收数据
	_, addr, err := a.UdpSocke.ReadFromUDP(remoteData)
	ErrCheck(err)
	//解析数据
	outCmd = *((*uint16)(unsafe.Pointer(&remoteData[0])))
	outpkg.RawData = remoteData
	outpkg.remoteAddr = addr
	return outpkg, outCmd
}

// 字节转结构体
func ByteToStruct[T any](b []byte) T {

	ot := *((*T)(unsafe.Pointer(&b[0])))
	return ot
}

func ErrCheck(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(0)
	}
}
